//
//  RYCHTTPRequestModel.m
//  RaiyiCommon
//
//  Created by zhiwei ma on 12-4-25.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "RYCHTTPRequestModel.h"
#import "RYCHTTPRequestQueue.h"
#import "RYCHTTPRequest.h"

#define RYCHTTPDEBUG

#if _HTTP_FLOW_RECORD_ALLOW_
long gHTTPFlowRecorder = 0;
#endif

@interface RYCHTTPRequestModel()
@property (nonatomic, retain) ASIHTTPRequest* httpRequest;
@end

@implementation RYCHTTPRequestModel
@synthesize delegate = _delegate;
@synthesize responseObject = _responseObject;
@synthesize error = _error;
@synthesize operation = _operation;
@synthesize httpRequest = _httpRequest;
@synthesize requestQueue = _requestQueue;

- (void)dealloc
{
    self.responseObject = nil;
    self.error = nil;
    [_httpRequest clearDelegatesAndCancel];
    [_httpRequest release];
    self.requestQueue = nil;
    [super dealloc];
}

- (id)initWithDelegate:(id<RYCHTTPRequestModelDelegate>)delegate
{
    self = [super init];
    if (self)
    {
        self.delegate = delegate;
    }
    return self;
}

- (void)sendRequest
{
    if (_httpRequest && [_httpRequest isExecuting])
    {
        [self cancelRequest];
    }
    
    self.httpRequest = [self request];
    if (nil == _httpRequest)
    {
        _state = RYCHTTPRequestModelState_Pending;
        return;
    }
    
    if (RYCHTTPRequestModelOperation_Refresh == _operation)//刷新
    {
        [_httpRequest clearCache];
    }
    
    _httpRequest.delegate = self;
    
    if (nil == _requestQueue)
    {
        self.requestQueue = [RYCHTTPRequestQueue sharedInstance];
       
    }
    [_requestQueue addRequest:_httpRequest];
#ifdef RYCHTTPDEBUG
    NSLog(@"request url= %@",[_httpRequest.url absoluteString]);
#endif
    _state = RYCHTTPRequestModelState_Loading;
}

- (void)cancelRequest
{
    if (_state == RYCHTTPRequestModelState_Loading)
    {
        [_httpRequest clearDelegatesAndCancel];
        _state = RYCHTTPRequestModelState_Pending;
    }
}

- (BOOL)isDone
{
    return (_state == RYCHTTPRequestModelState_Finished || _state == RYCHTTPRequestModelState_Failed) ? YES : NO;
}

- (BOOL)isFinished
{
    return (_state == RYCHTTPRequestModelState_Finished);
}

- (BOOL)isFailed
{
    return (_state == RYCHTTPRequestModelState_Failed);
}

- (BOOL)isLoading
{
    return (_state == RYCHTTPRequestModelState_Loading);
}

- (ASIHTTPRequest*)request
{
    return nil;
}

- (BOOL)handleResponseString:(id)aResponseString
{
    return YES;
}

- (void)reset
{
    [self cancelRequest];
    self.httpRequest = nil;
    self.responseObject = nil;
    self.error = nil;
    _state = RYCHTTPRequestModelState_Pending;
    _operation = RYCHTTPRequestModelOperation_Normal;
}

#pragma mark ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest*)request
{
    NSAssert(_httpRequest == request, @"");
    
    //通过NSData转成NSString,解决编码原因导致的中文乱码问题
//    NSString* rspString = request.responseString;
    NSString* rspString = [[[NSString alloc] initWithData:request.responseData encoding:NSUTF8StringEncoding] autorelease];
#ifdef RYCHTTPDEBUG
    NSLog(@"%s", __FUNCTION__);
    BOOL useCacheFlag = [request didUseCachedResponse];
    NSLog(@"response url = %@  useCache = %d",request.url.absoluteString, useCacheFlag);
    NSLog(@"data = %@", rspString);
#endif
    
#if _HTTP_FLOW_RECORD_ALLOW_
    extern long gHTTPFlowRecorder;
    NSInteger curRequestFlow = [[request responseData] length];
    if (NO == useCacheFlag)
    {
        gHTTPFlowRecorder += curRequestFlow;
    }
    NSInteger flowK = gHTTPFlowRecorder/1024;
    NSLog(@"http flow  curRequest=%dB, all=%dK(%dB)", curRequestFlow,flowK,(NSInteger)gHTTPFlowRecorder);
#endif
    
    BOOL ret = [self handleResponseString:rspString];
    if (ret)
    {
        _state = RYCHTTPRequestModelState_Finished;
        if (_delegate && [_delegate conformsToProtocol:@protocol(RYCHTTPRequestModelDelegate)])     
        {
            if ([_delegate respondsToSelector:@selector(didHTTPRequestModelFinished:)])
            {
                [_delegate didHTTPRequestModelFinished:self];
            }
        }
    }
    else 
    {
        _state = RYCHTTPRequestModelState_Failed;
        if (_delegate && [_delegate conformsToProtocol:@protocol(RYCHTTPRequestModelDelegate)])     
        {
            if ([_delegate respondsToSelector:@selector(didHTTPRequestModelFailed:)])
            {
                [_delegate didHTTPRequestModelFailed:self];
            }
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSAssert(_httpRequest == request, @"");
#ifdef RYCHTTPDEBUG
    NSLog(@"%s %@",__FUNCTION__, request.error);
#endif
    
    //ASIHTTPRequest的error描述是英文的，转成中文
    self.error = [request.error convertToCurrentLanguage];
   
    _state = RYCHTTPRequestModelState_Failed;
    if (_delegate && [_delegate conformsToProtocol:@protocol(RYCHTTPRequestModelDelegate)])     
    {
        if ([_delegate respondsToSelector:@selector(didHTTPRequestModelFailed:)])
        {
            [_delegate didHTTPRequestModelFailed:self];
        }
    }
}

@end

#pragma mark - NSError (ASIError)
@implementation NSError (ASIError)
- (NSError*)convertToCurrentLanguage
{
    NSString* desc = nil;
    switch (self.code)
    {
        case 1:
            desc = @"连接失败，请检查您的网络是否可用";
            break;
            
        case 2:
            desc = @"连接超时，您的网络情况不太良好";
            break;
        
        default:
            desc = @"连接失败，网络异常";
            break;
    }
    
    NSMutableDictionary* userinfo = [NSMutableDictionary dictionaryWithDictionary:self.userInfo];
    [userinfo setObject:desc forKey:NSLocalizedDescriptionKey];
    NSError* error = [NSError errorWithDomain:self.domain code:self.code userInfo:userinfo];
    return error;
}
@end
